package mvp.com.bbc.rcjavaretrofitdaggermvp.mvp.utils;

import android.database.sqlite.SQLiteDatabase;

import com.anye.greendao.gen.DaoMaster;
import com.anye.greendao.gen.DaoSession;
import com.anye.greendao.gen.InfoBeanDao;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

import mvp.com.bbc.rcjavaretrofitdaggermvp.app.BaseApplication;
import mvp.com.bbc.rcjavaretrofitdaggermvp.bean.InfoBean;


/**
 * Created by ${cbf} on 2017/11/26.
 */

public class InfoBeanUtils {

    private DaoMaster.DevOpenHelper openHelper;

    /**
     * 查询所有列表数据
     **/
    public List<InfoBean> querInfoList() {
        DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        InfoBeanDao beanDao = daoSession.getInfoBeanDao();
        QueryBuilder<InfoBean> qb = beanDao.queryBuilder();
        List<InfoBean> list = qb.list();
        return list;
    }

    /**
     * 获取可读的数据库
     */
    private SQLiteDatabase getReadableDatabase() {
        if (openHelper == null) {
            openHelper = new DaoMaster.DevOpenHelper(BaseApplication.getContext(), "notes-db", null);
        }
        SQLiteDatabase db = openHelper.getReadableDatabase();
        return db;
    }

    /**
     * 获取可写数据库
     */
    private SQLiteDatabase getWritableDatabase() {
        if (openHelper == null) {
            openHelper = new DaoMaster.DevOpenHelper(BaseApplication.getContext(), "notes-db", null);
        }
        SQLiteDatabase db = openHelper.getWritableDatabase();
        return db;
    }

    /**
     * 根据用id来进行查询
     */
    public List<InfoBean> querInfoList(int Id) {
        DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        InfoBeanDao beanDao = daoSession.getInfoBeanDao();
        QueryBuilder<InfoBean> qb = beanDao.queryBuilder();
        qb.where(InfoBeanDao.Properties.ID.ge(Id)).orderDesc(InfoBeanDao.Properties.ID);
        List<InfoBean> list = qb.list();
        return list;
    }

    /**
     * 更新数据
     */
    public void Update(InfoBean infoBean) {
        DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        InfoBeanDao dao = daoSession.getInfoBeanDao();
        dao.update(infoBean);
    }

    /**
     * 删除全部数据
     */
    public void DeleteAll() {
        InfoBeanDao dao = new DaoMaster(getReadableDatabase()).newSession().getInfoBeanDao();
        dao.deleteAll();
    }

    /**
     * 根据ID来进行删除
     */
    public void DeleteId(int Id) {
        InfoBeanDao dao = new DaoMaster(getReadableDatabase()).newSession().getInfoBeanDao();
        QueryBuilder<InfoBean> qb = dao.queryBuilder();
        QueryBuilder<InfoBean> beanQueryBuilder = qb.where(InfoBeanDao.Properties.ID.ge(Id)).orderDesc(InfoBeanDao.Properties.ID);
        List<InfoBean> list = beanQueryBuilder.list();
        dao.delete(list.remove(Id));
    }
    //
}
